/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 
 *	@author: hejing
 *	@date: 2012-11-28-下午03:37:50
 */
public class DigestUtil {
    public final static String MD5 = "MD5";  
    public final static String NONE = "NONE";  
    public static final String SHA_1 = "SHA-1";
    public final static String SHA_256 = "SHA-256";  
    public final static String SHA_512 = "SHA-512";  
    public final static String SHA_384 = "SHA-384"; 
    
    /** 
     * 加密文件算法 
     *  
     * @param filename 
     *            需要加密的文件名 
     * @param algorithm 
     *            加密算法名 
     */  
    public static void digestFile(String filename, String algorithm) {  
        byte[] b = new byte[1024 * 4];  
        int len = 0;  
        FileInputStream fis = null;  
        FileOutputStream fos = null;  
        try {  
            MessageDigest md = MessageDigest.getInstance(algorithm);  
            fis = new FileInputStream(filename);  
            while ((len = fis.read(b)) != -1) {  
                md.update(b, 0, len);  
            }  
            byte[] digest = md.digest();  
            StringBuffer fileNameBuffer = new StringBuffer(128).append(filename).append(".").append(algorithm);  
            fos = new FileOutputStream(fileNameBuffer.toString());  
            OutputStream encodedStream = new Base64OutputStream(fos);  
            encodedStream.write(digest);  
            encodedStream.flush();  
            encodedStream.close();  
        } catch (Exception e) {  
            System.out.println("Error computing Digest: " + e);  
        } finally {  
            try {  
                if (fis != null)  
                    fis.close();  
            } catch (Exception ignored) {  
            }  
            try {  
                if (fos != null)  
                    fos.close();  
            } catch (Exception ignored) {  
            }  
        }  
    }  
  
    /** 
     * 加密密码算法 
     *  
     * @param pass 
     *            需要加密的原始密码 
     * @param algorithm 
     *            加密算法名称 
     * @return 加密后的密码 
     * @throws NoSuchAlgorithmException 
     *             当加密算法不可用时抛出此异常 
     */  
    public static String digestString(String password, String alg) throws NoSuchAlgorithmException {  
        String newPass;  
        if (alg == null || MD5.equals(alg)) {  
            newPass = DigestUtils.md5Hex(password);  
        } else if (NONE.equals(alg)) {  
            newPass = password;  
        } else if(SHA_1.equals(alg)){
        	newPass=DigestUtils.sha1Hex(password);
        } else if (SHA_256.equals(alg)) {  
            newPass = DigestUtils.sha256Hex(password);  
        } else if (SHA_384.equals(alg)) {  
            newPass = DigestUtils.sha384Hex(password);  
        } else if (SHA_512.equals(alg)) {  
            newPass = DigestUtils.sha512Hex(password);  
        } else {  
            newPass = DigestUtils.shaHex(password);  
        }  
        return newPass;  
    }  
  
    /** 
     * 加密密码算法，默认的加密算法是SHA-256  
     *  
     * @param password 
     *            未加密的密码 
     * @return String 加密后的密码,64位字符串
     */  
    public static String digestPassword(String password) {  
        try {  
            if (password != null && !"".equals(password)) {  
                return digestString(password, SHA_256);  
            } else  
                return null;  
        } catch (NoSuchAlgorithmException nsae) {  
            throw new RuntimeException("Security error: " + nsae);  
        }  
    }  
  
    /** 
     * 判断密码是不是相等，默认的加密算法是SHA-256 
     *  
     * @param beforePwd 
     *            要判断的密码 
     * @param afterPwd 
     *            加密后的数据库密码 
     * @return Boolean true 密码相等 
     */  
    public static boolean isPasswordEnable(String beforePwd, String afterPwd) {  
        if (beforePwd != null && !"".equals(beforePwd)) {  
            String password = digestPassword(beforePwd);  
            return afterPwd.equals(password);  
        } else  
            return false;  
    }  
  
    public static void main(String[] args) throws NoSuchAlgorithmException {
    	long begin=System.currentTimeMillis();
    	for(int i=0;i<100000;i++)
    		DigestUtil.digestPassword("rqrtqwtwqtrwqytqwfdafdsgheuherwyrewuerygtew");
        long end=System.currentTimeMillis();
        System.out.println("cost="+(end-begin));
        System.out.println(DigestUtil.digestPassword("rqrtqwtwqtrwqytqwfdafdsgheuherwyrewuerygtew"));  
        System.out.println(DigestUtil.isPasswordEnable("123456", DigestUtil.digestPassword("123456")));  
    }  
}
